package com.wf.mock.app.mina.dto;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.JSONObject;
import com.wf.mock.app.mina.MessageIntentType;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class RawMessageDTO {

	public final static RawMessageDTO EMPTYRAWMESSAGE = new RawMessageDTO();

	private MessageIntentType type = MessageIntentType.EMPTY;

	private JSONObject msgBody = new JSONObject();

	public String getMsgMarkId() {
		return msgBody.getString("markId");
	}

	@Override
	public String toString() {
		return type + msgBody.toJSONString();
	}

	public static RawMessageDTO create(Object msgObj) {

		if (msgObj == null || StringUtils.isBlank(msgObj.toString())) {
			return EMPTYRAWMESSAGE;
		}

		String msg = msgObj.toString().trim();
		MessageIntentType type = MessageIntentType.praseMessageIntentType(msg);

		String msgBody = msg;
		int prefixLength = type.getPreffix().length();
		if (msg.length() >= prefixLength) {
			msgBody = msg.substring(prefixLength);
		}

		return new RawMessageDTO(type, JSONObject.parseObject(msgBody));

	}

}
